import json
import hashlib
import re
import time
import paramiko
from datetime import datetime, timedelta


class CommonUntil():
    def __init__(self, res_log):
        self.res_log = res_log

    def exec_ssh_command(self, ip_addre, username, password, command):
        """
        远程执行shell命令并返回结果。

        :param ip: 远程服务器的IP地址。
        :param username: 用于SSH连接的用户名。
        :param password: 用于SSH连接的密码。
        :param command: 需要在远程服务器上执行的shell命令。
        :return: 远程命令的输出。
        """
        # 创建SSH对象
        ssh = paramiko.SSHClient()

        # 允许连接不在known_hosts中主机的连接。
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            # 连接到远程服务器
            ssh.connect(ip_addre, username=username, password=password)

            # 执行命令
            stdin, stdout, stderr = ssh.exec_command(command)

            # 获取命令执行结果
            output = stdout.read().decode('utf-8')
            res_dic = {}
            res_dic["msg"] = output
            print(res_dic)
            print(output)
            return res_dic
        except Exception as e:
            print(f"发生错误：{e}")
        finally:
            # 关闭SSH连接
            ssh.close()

    def get_res_is_success(self, res, type, is_return_data=False):
        """
        获取res的 success字段，true表示成功，false表示失败
        :param res: json
        :param type: "【获取数据库表】{} {} 查询 PASS, 获取表：{} {}
        :return:
        """
        res_json = ''
        try:
            res_json = res.json()
            res_is_success = res_json["success"]
            res_msg = res_json["msg"]
            if res_is_success == True:
                res = "{} PASS {}".format(type, "\r\n")
                self.res_log.write(res.encode('utf-8'))
            else:
                res = "{} ERROR，错误日志 {} {}".format(type, res_msg, "\r\n")
                print(res)
                self.res_log.write(res.encode('utf-8'))
        except Exception as e:
            res = "{} ERROR, res 结果转换失败, {} 报错：{}".format(type, res, e, "\r\n")
            self.res_log.write(res.encode('utf-8'))
            return res
        if is_return_data:
            return res_json

    def generate_time(self, offset_days=0):
        if not isinstance(offset_days, int):
            raise ValueError("Offset days must be an integer.")
        # 获取当前时间
        current_time = datetime.now()

        # 增加指定天数
        target_time = current_time + timedelta(offset_days)

        # 将时间格式化为指定格式的字符串
        formatted_time = target_time.strftime("%Y-%m-%d 00:00:00")

        return formatted_time

    def generate_timestamp_md5(self):
        # 获取当前时间戳
        current_timestamp = str(int(time.time()))
        time.sleep(1)

        # 对时间戳进行 MD5 加密
        md5_hash = hashlib.md5(current_timestamp.encode()).hexdigest()

        return md5_hash

    def get_res_json_value(self, res, col):
        """
        get_res_json_value(res, ['data'])
        :param res:  res 是 {'code': 0, 'msg': '成功', 'exceptionStack': None, 'data': 13234809144864, 'failed': False, 'success': True}
        :param col: data字段
        :return: 13234809144864
        """
        try:
            # 解析 JSON 数据
            data = res.json()
            # print("即将解析的 json 是{}".format(data))
            # 根据提供的字段名提取对应的值
            if col in data:
                return data[col]
            elif 'data' in data and col in data['data']:
                return data['data'][col]
            elif 'totalList' in data['data'] and data['data']['totalList']:
                # 假设只取第一个元素的字段值
                return data['data']['totalList'][0].get(col, None)
            else:
                return None
        except Exception as e:
            print("Error:", e)
            return None

    def update_task_id_in_url(self, url, key, task_id=''):
        """
        update_task_id_in_url("http://st1:12345/dolphinscheduler/whaletunnel/api/v1/job/task/13510099281056","task","") 表示清空task后面url
        :param url:
        :param key:
        :param task:
        :return:
        """
        if task_id == '':
            url = re.sub(r'/{}/.*\d+'.format(key), '/{}'.format(key), url)
        else:
            url = url + "/" + task_id
        return url


if __name__ == '__main__':
    c = CommonUntil("./")
    # print(c.generate_timestamp_md5())
    # print(c.generate_timestamp_md5())
    c.remote_execute_command("192.168.124.78", "whale_ops", "QWer12#$",
                             "cd /data/whalestudio/DB;sh upgrade.sh 155 new | tee upgrade.txt")
